﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Util
{
    public class HttpClient
    {
        /// <summary>
        /// Seivice URL
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
        /// <summary>
        /// Cookie，保证登录后，所有访问持有一个Cookie；
        /// </summary>
        static CookieContainer Cookie = new CookieContainer();

        /// <summary>
        /// HTTP访问POST
        /// </summary>
        public async Task<string> AsyncRequest_KingDee()
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //必须加上这一句，根据需要更改值

            HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            httpRequest.CookieContainer = Cookie;
            httpRequest.Timeout = 1000 * 60 * 10;//10min

            using (Stream reqStream = await httpRequest.GetRequestStreamAsync())
            {
                JObject jObj = new JObject();
                jObj.Add("format", 1);
                jObj.Add("useragent", "ApiClient");
                jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
                jObj.Add("parameters", Content);
                jObj.Add("timestamp", DateTime.Now);
                jObj.Add("v", "1.0");
                string sContent = jObj.ToString();
                var bytes = UnicodeEncoding.UTF8.GetBytes(sContent);
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
            }
            //获取服务器响应
            using (var webResponse = await httpRequest.GetResponseAsync())
            //将响应进行流处理
            using (var repStream = webResponse.GetResponseStream())
            {
                using (var reader = new StreamReader(repStream))
                {
                    return ValidateResult(reader.ReadToEnd());
                }
            }
        }

        /// <summary>
        /// HTTP访问POST
        /// </summary>
        public async Task<string> AsyncRequest()
        {
            //ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验
            //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //必须加上这一句，根据需要更改值

            HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            httpRequest.CookieContainer = Cookie;
            httpRequest.Timeout = 1000 * 60 * 10;//10min

            using (Stream reqStream = await httpRequest.GetRequestStreamAsync())
            {
                var bytes = UnicodeEncoding.UTF8.GetBytes(Content);
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
            }
            //获取服务器响应
            using (var webResponse = await httpRequest.GetResponseAsync())
            //将响应进行流处理
            using (var repStream = webResponse.GetResponseStream())
            {
                using (var reader = new StreamReader(repStream))
                {
                    return ValidateResult(reader.ReadToEnd());
                }
            }
        }

        /// <summary>
        /// HTTP访问POST
        /// </summary>
        public string Request()
        {
           // ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验
            //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //必须加上这一句，根据需要更改值
            try
            {

                HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
                httpRequest.Method = "POST";
                httpRequest.ContentType = "application/json";
                httpRequest.CookieContainer = Cookie;
                httpRequest.Timeout = 1000 * 60 * 10;//10min

                using (Stream reqStream = httpRequest.GetRequestStream())
                {
                    //JObject jObj = new JObject();
                    //jObj.Add("format", 1);
                    //jObj.Add("useragent", "ApiClient");
                    //jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
                    //jObj.Add("parameters", Content);
                    //jObj.Add("timestamp", DateTime.Now);
                    //jObj.Add("v", "1.0");
                    //string sContent = jObj.ToString();
                    var bytes = UnicodeEncoding.UTF8.GetBytes(Content);
                    reqStream.Write(bytes, 0, bytes.Length);
                    reqStream.Flush();
                }
                //获取服务器响应

                using (var webResponse = httpRequest.GetResponse())
                //将响应进行流处理
                using (var repStream = webResponse.GetResponseStream())
                {
                    using (var reader = new StreamReader(repStream))
                    {
                        return ValidateResult(reader.ReadToEnd());
                    }
                }
            }
            catch (Exception ex)
           {
                return ex.Message;
            }
        }
        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                return responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;

        }
    }
}
